<template>
  <div class="min-h-screen bg-gray-50 ">
    <!-- Header Section -->
    <div class="bg-white  border-b border-gray-200 ">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <button 
              @click="$router.go(-1)"
              class="p-2 rounded-lg hover:bg-gray-100  transition-colors"
            >
              <svg class="w-5 h-5 text-gray-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
              </svg>
            </button>
            <div>
              <h1 class="text-2xl font-bold text-gray-900 ">{{ agent.name }}</h1>
              <p class="text-sm text-gray-500 ">{{ getCategoryLabel(agent.category) }}</p>
            </div>
          </div>
          
          <div class="flex items-center space-x-3">
            <button 
              @click="toggleFavorite"
              class="p-2 rounded-lg hover:bg-gray-100  transition-colors"
            >
              <svg 
                class="w-5 h-5 transition-colors" 
                :class="isFavorited ? 'text-red-500 fill-current' : 'text-gray-400'"
                fill="none" 
                stroke="currentColor" 
                viewBox="0 0 24 24"
              >
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
              </svg>
            </button>
            
            <button 
              @click="shareAgent"
              class="p-2 rounded-lg hover:bg-gray-100  transition-colors"
            >
              <svg class="w-5 h-5 text-gray-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z" />
              </svg>
            </button>
            
            <button 
              @click="useAgent"
              class="px-4 py-2 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg hover:from-blue-600 hover:to-blue-700 transition-all duration-200 font-medium text-sm"
            >
              Use Agent
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Main Content -->
        <div class="lg:col-span-2 space-y-6">
          <!-- Description -->
          <div class="bg-white  rounded-xl shadow-sm border border-gray-200  p-6">
            <h2 class="text-lg font-semibold text-gray-900  mb-3">Description</h2>
            <p class="text-gray-600  leading-relaxed">{{ agent.description }}</p>
          </div>

          <!-- System Prompt -->
          <div class="bg-white  rounded-xl shadow-sm border border-gray-200  p-6">
            <h2 class="text-lg font-semibold text-gray-900  mb-3">System Prompt</h2>
            <div class="bg-gray-50  rounded-lg p-4">
              <pre class="text-sm text-gray-700  whitespace-pre-wrap font-mono">{{ agent.prompt }}</pre>
            </div>
          </div>

          <!-- Agent Capabilities -->
          <div class="bg-white  rounded-xl shadow-sm border border-gray-200  p-6">
            <h2 class="text-lg font-semibold text-gray-900  mb-4">Agent Capabilities</h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div v-if="agent.primaryFunction" class="bg-blue-50  rounded-lg p-4">
                <h3 class="text-sm font-medium text-blue-900  mb-2">Primary Function</h3>
                <p class="text-sm text-blue-700 ">{{ agent.primaryFunction }}</p>
              </div>
              <div v-if="agent.specialization" class="bg-green-50  rounded-lg p-4">
                <h3 class="text-sm font-medium text-green-900  mb-2">Specialization</h3>
                <p class="text-sm text-green-700 ">{{ agent.specialization }}</p>
              </div>
              <div v-if="agent.keySkills" class="bg-purple-50  rounded-lg p-4">
                <h3 class="text-sm font-medium text-purple-900  mb-2">Key Skills</h3>
                <p class="text-sm text-purple-700 ">{{ agent.keySkills }}</p>
              </div>
            </div>
          </div>

          <!-- Tool Library -->
          <div class="bg-white  rounded-xl shadow-sm border border-gray-200  p-6">
            <h2 class="text-lg font-semibold text-gray-900  mb-4">Tool Library</h2>
            
            <!-- Built-in Tools -->
            <div v-if="agent.toolLibrary?.builtinTools?.length" class="mb-6">
              <h3 class="text-sm font-medium text-gray-700  mb-3 flex items-center">
                <span class="w-2 h-2 bg-blue-500 rounded-full mr-2"></span>
                Built-in Tools
              </h3>
              <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div 
                  v-for="tool in agent.toolLibrary.builtinTools" 
                  :key="tool.name"
                  class="flex items-center p-3 bg-gray-50  rounded-lg"
                >
                  <span class="text-lg mr-3">{{ tool.icon }}</span>
                  <div>
                    <p class="text-sm font-medium text-gray-900 ">{{ tool.name }}</p>
                    <p class="text-xs text-gray-500 ">{{ tool.description }}</p>
                  </div>
                </div>
              </div>
            </div>

            <!-- MCP Services -->
            <div v-if="agent.toolLibrary?.mcpServices?.length" class="mb-6">
              <h3 class="text-sm font-medium text-gray-700  mb-3 flex items-center">
                <span class="w-2 h-2 bg-purple-500 rounded-full mr-2"></span>
                MCP Services
              </h3>
              <div class="space-y-3">
                <div 
                  v-for="service in agent.toolLibrary.mcpServices" 
                  :key="service.name"
                  class="p-4 bg-gray-50  rounded-lg"
                >
                  <div class="flex items-start justify-between mb-2">
                    <h4 class="text-sm font-medium text-gray-900 ">{{ service.name }}</h4>
                  </div>
                  <p class="text-xs text-gray-500  mb-2">{{ service.description }}</p>
                  <div class="bg-gray-100  rounded-md p-2 mb-2">
                    <p class="text-xs text-gray-700  font-mono">
                      <span class="font-medium">Install Command:</span><br>
                      claude add mcp {{ service.serverUrl }}
                    </p>
                  </div>
                  <p v-if="service.capabilities" class="text-xs text-gray-600 ">
                    <span class="font-medium">Capabilities:</span> {{ service.capabilities }}
                  </p>
                </div>
              </div>
            </div>

            <!-- Custom API Services -->
            <div v-if="agent.toolLibrary?.apiServices?.length" class="mb-6">
              <h3 class="text-sm font-medium text-gray-700  mb-3 flex items-center">
                <span class="w-2 h-2 bg-green-500 rounded-full mr-2"></span>
                Custom API Services
              </h3>
              <div class="space-y-3">
                <div 
                  v-for="api in agent.toolLibrary.apiServices" 
                  :key="api.name"
                  class="p-4 bg-gray-50  rounded-lg"
                >
                  <div class="flex items-start justify-between mb-2">
                    <h4 class="text-sm font-medium text-gray-900 ">{{ api.name }}</h4>
                    <div class="flex items-center space-x-2">
                      <span class="text-xs px-2 py-1 bg-green-100  text-green-700  rounded-full">
                        {{ api.method }}
                      </span>
                      <span class="text-xs px-2 py-1 bg-gray-100  text-gray-700  rounded-full">
                        {{ getApiAuthLabel(api.auth) }}
                      </span>
                    </div>
                  </div>
                  <p class="text-xs text-gray-500  mb-2">{{ api.description }}</p>
                  <p class="text-xs text-gray-600 ">
                    <span class="font-medium">Endpoint:</span> {{ api.endpoint }}
                  </p>
                  <p v-if="api.capabilities" class="text-xs text-gray-600  mt-1">
                    <span class="font-medium">Capabilities:</span> {{ api.capabilities }}
                  </p>
                </div>
              </div>
            </div>

            <!-- Personal Expertise -->
            <div v-if="agent.toolLibrary?.expertise" class="mb-6">
              <h3 class="text-sm font-medium text-gray-700  mb-3 flex items-center">
                <span class="w-2 h-2 bg-orange-500 rounded-full mr-2"></span>
                Personal Expertise
              </h3>
              <div class="p-4 bg-gray-50  rounded-lg">
                <div v-if="agent.toolLibrary.expertise.domain" class="mb-3">
                  <h4 class="text-sm font-medium text-gray-900  mb-1">Domain</h4>
                  <p class="text-xs text-gray-600 ">{{ agent.toolLibrary.expertise.domain }}</p>
                </div>
                <div v-if="agent.toolLibrary.expertise.experience" class="mb-3">
                  <h4 class="text-sm font-medium text-gray-900  mb-1">Experience</h4>
                  <p class="text-xs text-gray-600 ">{{ agent.toolLibrary.expertise.experience }}</p>
                </div>
                <div v-if="agent.toolLibrary.expertise.problemSolving" class="mb-3">
                  <h4 class="text-sm font-medium text-gray-900  mb-1">Problem Solving</h4>
                  <p class="text-xs text-gray-600 ">{{ agent.toolLibrary.expertise.problemSolving }}</p>
                </div>
                <div v-if="agent.toolLibrary.expertise.bestPractices" class="mb-3">
                  <h4 class="text-sm font-medium text-gray-900  mb-1">Best Practices</h4>
                  <p class="text-xs text-gray-600 ">{{ agent.toolLibrary.expertise.bestPractices }}</p>
                </div>
                <div v-if="agent.toolLibrary.expertise.uploadedFiles?.length" class="mt-3">
                  <h4 class="text-sm font-medium text-gray-900  mb-2">Knowledge Files</h4>
                  <div class="space-y-2">
                    <div 
                      v-for="file in agent.toolLibrary.expertise.uploadedFiles" 
                      :key="file.name"
                      class="flex items-center p-2 bg-white  rounded border"
                    >
                      <svg class="w-4 h-4 text-gray-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                      </svg>
                      <span class="text-xs text-gray-600 ">{{ file.name }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Sidebar -->
        <div class="space-y-6">
          <!-- Pricing & Usage -->
          <div class="bg-white  rounded-xl shadow-sm border border-gray-200  p-6">
            <h2 class="text-lg font-semibold text-gray-900  mb-4">Pricing & Usage</h2>
            
            <div class="space-y-4">
              <div class="flex items-center justify-between">
                <span class="text-sm text-gray-600 ">Model</span>
                <span class="text-sm font-medium text-gray-900 ">{{ getPricingLabel(agent.pricing.model) }}</span>
              </div>
              
              <div v-if="agent.pricing.model !== 'free'" class="flex items-center justify-between">
                <span class="text-sm text-gray-600 ">Price</span>
                <span class="text-sm font-medium text-gray-900 ">${{ agent.pricing.price }}/month</span>
              </div>
              
              <div v-if="agent.pricing.model === 'freemium'" class="flex items-center justify-between">
                <span class="text-sm text-gray-600 ">Usage Limit</span>
                <span class="text-sm font-medium text-gray-900 ">{{ agent.pricing.usageLimit }} requests</span>
              </div>
            </div>
            
            <button 
              @click="useAgent"
              class="w-full mt-4 px-4 py-2 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg hover:from-blue-600 hover:to-blue-700 transition-all duration-200 font-medium text-sm"
            >
              Start Using Agent
            </button>
          </div>

          <!-- Agent Stats -->
          <div class="bg-white  rounded-xl shadow-sm border border-gray-200  p-6">
            <h2 class="text-lg font-semibold text-gray-900  mb-4">Agent Stats</h2>
            
            <div class="space-y-4">
              <div class="flex items-center justify-between">
                <span class="text-sm text-gray-600 ">Created</span>
                <span class="text-sm font-medium text-gray-900 ">{{ formatDate(agent.createdAt) }}</span>
              </div>
              
              <div class="flex items-center justify-between">
                <span class="text-sm text-gray-600 ">Usage Count</span>
                <span class="text-sm font-medium text-gray-900 ">{{ agent.usageCount || 0 }}</span>
              </div>
              
              <div class="flex items-center justify-between">
                <span class="text-sm text-gray-600 ">Rating</span>
                <div class="flex items-center">
                  <span class="text-sm font-medium text-gray-900  mr-1">{{ agent.rating || 4.5 }}</span>
                  <div class="flex">
                    <svg 
                      v-for="i in 5" 
                      :key="i"
                      class="w-3 h-3"
                      :class="i <= (agent.rating || 4.5) ? 'text-yellow-400' : 'text-gray-300'"
                      fill="currentColor" 
                      viewBox="0 0 20 20"
                    >
                      <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                    </svg>
                  </div>
                </div>
              </div>
              
              <div class="flex items-center justify-between">
                <span class="text-sm text-gray-600 ">Status</span>
                <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800  ">
                  <span class="w-1.5 h-1.5 bg-green-400 rounded-full mr-1.5"></span>
                  Online
                </span>
              </div>
            </div>
          </div>

          <!-- Creator Info -->
          <div class="bg-white  rounded-xl shadow-sm border border-gray-200  p-6">
            <h2 class="text-lg font-semibold text-gray-900  mb-4">Creator</h2>
            
            <div class="flex items-center space-x-3">
              <div class="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
                <span class="text-white font-medium text-sm">{{ agent.creator?.name?.charAt(0) || 'U' }}</span>
              </div>
              <div>
                <p class="text-sm font-medium text-gray-900 ">{{ agent.creator?.name || 'Anonymous' }}</p>
                <p class="text-xs text-gray-500 ">{{ agent.creator?.agentsCount || 0 }} agents created</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useRoute } from 'vue-router'

  const route = useRoute()
  const isFavorited = ref(false)

  // Mock agent data - in real app, this would come from API
  const agent = ref({
    id: route.params.id,
    name: 'AI Writing Assistant',
    category: 'writing',
    customCategory: '',
    description: 'A powerful AI writing assistant that helps you create compelling content, from blog posts to marketing copy. Trained on millions of high-quality articles and optimized for various writing styles and tones.',
    prompt: 'You are an expert writing assistant with years of experience in content creation, copywriting, and editorial work. You excel at understanding audience needs, crafting compelling narratives, and adapting your writing style to match different brands and purposes. Always prioritize clarity, engagement, and authenticity in your writing.',
    primaryFunction: 'Content Creation & Copywriting',
    specialization: 'Marketing Copy & Blog Writing',
    keySkills: 'SEO Writing, Brand Voice Development, Content Strategy',
    toolLibrary: {
      selectedTypes: ['builtin', 'mcp', 'api', 'expertise'],
      builtinTools: [
        {
          name: 'Web Search',
          description: 'Search the web for real-time information',
          icon: '🔍',
          color: 'bg-blue-500',
          isSelected: true
        },
        {
          name: 'File Manager',
          description: 'Read, write, and manage files',
          icon: '📁',
          color: 'bg-green-500',
          isSelected: true
        }
      ],
      mcpServices: [
        {
          name: 'Grammarly API',
          serverUrl: 'grammarly-mcp',
          auth: 'api-key',
          capabilities: 'Grammar checking, style suggestions, tone analysis',
          description: 'Advanced grammar and style checking service'
        }
      ],
      apiServices: [
        {
          name: 'Content Research API',
          endpoint: 'https://api.contentresearch.com/v1/search',
          method: 'POST',
          auth: 'bearer',
          timeout: 30,
          credentials: '',
          headers: '{"Content-Type": "application/json"}',
          requestBody: '{"query": "{{user_query}}", "limit": 10}',
          description: 'Research trending topics and content ideas',
          capabilities: 'Topic research, trend analysis, content suggestions'
        }
      ],
      expertise: {
        inputMethod: 'manual',
        domain: 'Digital Marketing & Content Strategy',
        experience: '5+ years in content marketing, worked with 100+ brands',
        problemSolving: 'Focus on audience-first approach, data-driven content decisions',
        bestPractices: 'A/B testing, SEO optimization, brand consistency',
        caseStudies: 'Increased client engagement by 300% through targeted content',
        insights: 'Content that resonates requires deep audience understanding',
        uploadedFiles: [
          { name: 'content_guidelines.pdf', size: 1024000 },
          { name: 'brand_voice_guide.docx', size: 512000 }
        ],
        fileDescription: 'Brand guidelines and content best practices'
      }
    },
    knowledgeBase: {
      type: 'api',
      textContent: '',
      files: [],
      apiEndpoint: 'https://api.knowledgebase.com/v1/query',
      authMethod: 'api-key',
      requestMethod: 'POST',
      updateFrequency: 'daily'
    },
    pricing: {
      model: 'freemium',
      price: 9.99,
      usageLimit: 1000
    },
    createdAt: new Date('2024-01-15'),
    usageCount: 1247,
    rating: 4.8,
    creator: {
      name: 'Sarah Chen',
      agentsCount: 12
    }
  })

  // Dropdown options (same as CreateAgentPage)
  const categoryOptions = [
    { value: 'coding', label: 'Coding Agent' },
    { value: 'writing', label: 'Writing Agent' },
    { value: 'design', label: 'Design Agent' },
    { value: 'marketing', label: 'Marketing Agent' },
    { value: 'customer-service', label: 'Customer Service' },
    { value: 'data-analysis', label: 'Data Analysis' },
    { value: 'education', label: 'Education' },
    { value: 'healthcare', label: 'Healthcare' },
    { value: 'finance', label: 'Finance' },
    { value: 'other', label: 'Other' }
  ]

  const pricingOptions = [
    { value: 'free', label: 'Free' },
    { value: 'paid', label: 'Paid' },
    { value: 'freemium', label: 'Freemium' }
  ]

  const mcpAuthOptions = [
    { value: 'none', label: 'No Authentication' },
    { value: 'token', label: 'Token' },
    { value: 'oauth', label: 'OAuth' }
  ]

  const apiAuthOptions = [
    { value: 'none', label: 'No Authentication' },
    { value: 'bearer', label: 'Bearer Token' },
    { value: 'api-key', label: 'API Key' },
    { value: 'basic', label: 'Basic Auth' },
    { value: 'oauth', label: 'OAuth' }
  ]

  const knowledgeAuthOptions = [
    { value: 'none', label: 'No Authentication' },
    { value: 'token', label: 'Token' },
    { value: 'api-key', label: 'API Key' }
  ]

  const updateFrequencyOptions = [
    { value: 'realtime', label: 'Real-time' },
    { value: 'hourly', label: 'Hourly' },
    { value: 'daily', label: 'Daily' },
    { value: 'weekly', label: 'Weekly' },
    { value: 'manual', label: 'Manual' }
  ]

  // Helper methods
  const getCategoryLabel = (value) => {
    if (value === 'other' && agent.value.customCategory) {
      return agent.value.customCategory
    }
    const category = categoryOptions.find(cat => cat.value === value)
    return category ? category.label : ''
  }

  const getPricingLabel = (value) => {
    const pricing = pricingOptions.find(p => p.value === value)
    return pricing ? pricing.label : ''
  }

  const getMcpAuthLabel = (value) => {
    const auth = mcpAuthOptions.find(a => a.value === value)
    return auth ? auth.label : ''
  }

  const getApiAuthLabel = (value) => {
    const auth = apiAuthOptions.find(a => a.value === value)
    return auth ? auth.label : ''
  }

  const getKnowledgeAuthLabel = (value) => {
    const auth = knowledgeAuthOptions.find(a => a.value === value)
    return auth ? auth.label : ''
  }

  const getUpdateFrequencyLabel = (value) => {
    const freq = updateFrequencyOptions.find(f => f.value === value)
    return freq ? freq.label : ''
  }

  const formatDate = (date) => {
    return new Date(date).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    })
  }

  // Actions
  const toggleFavorite = () => {
    isFavorited.value = !isFavorited.value
    // In real app, this would make an API call
  }

  const shareAgent = () => {
    if (navigator.share) {
      navigator.share({
        title: agent.value.name,
        text: agent.value.description,
        url: window.location.href
      })
    } else {
      // Fallback to clipboard
      navigator.clipboard.writeText(window.location.href)
      // Show toast notification
    }
  }

  const useAgent = () => {
    // In real app, this would redirect to agent usage interface
    console.log('Using agent:', agent.value.name)
  }

  onMounted(() => {
    // In real app, fetch agent data based on route.params.id
    console.log('Loading agent:', route.params.id)
  })
</script>
